package net.roobook.cms.common.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.roobook.cms.common.dao.BaseMapper;
import net.roobook.cms.common.entity.BaseEntity;
import net.roobook.cms.common.entity.SearchEntity;
import net.roobook.cms.common.exception.CmsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author cos
 * @email 327878610@qq.com
 * @link https://roobook.net
 * @Description 基类Service
 * @date 2023/9/25 16:51
 **/
@Transactional(readOnly = true)
public abstract class CrudService <D extends BaseMapper<T>, T extends BaseEntity<T>>
        extends BaseService {

    /**
     * 持久层对象
     */
    @Autowired
    protected D dao;

    /**
     * 增
     * @param t
     * @return
     */
    @Transactional(readOnly = false)
    public int add(T t){
        return dao.insertSelective(t);
    };

    /**
     * 改
     * @param t
     * @return
     */
    @Transactional(readOnly = false)
    public int update(T t){
        return dao.updateByPrimaryKeySelective(t);
    };

    /**
     * 删
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    public int delete(String id){
        return dao.deleteByPrimaryKey(id);
    };

    /**
     * 分页查询
     * @param params
     * @return
     */
    public PageInfo<T> queryListByPage(SearchEntity params){
        if(params.getPageNum() == null || params.getPageNum() == 0) {
            params.setPageNum(1);
        }
        if(params.getPageSize() == null || params.getPageSize() == 0) {
            params.setPageSize(10);
        }
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<T> list = dao.queryListByPage(params.getEntity());
        PageInfo<T> page = new PageInfo<T>(list);
        return page;
    };

    /**
     * 根据ID查询实体
     * @param id
     * @return
     */
    public T queryEntityById(String id){
      return dao.selectByPrimaryKey(id);
    };
}
